package ua.kharkov.knure.dereza.summarytask4.command;

import java.math.BigDecimal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.knure.dereza.summarytask4.core.Constants;
import ua.kharkov.knure.dereza.summarytask4.db.bean.ClientBean;
import ua.kharkov.knure.dereza.summarytask4.db.dao.CardDAO;
import ua.kharkov.knure.dereza.summarytask4.db.dao.DAOFactory;
import ua.kharkov.knure.dereza.summarytask4.db.dao.StatusDAO;
import ua.kharkov.knure.dereza.summarytask4.db.dao.mysql.MysqlDAOFactory;
import ua.kharkov.knure.dereza.summarytask4.db.dto.CardDTO;
import ua.kharkov.knure.dereza.summarytask4.db.dto.StatusDTO;

/**
 * Performs replenish of money
 * 
 * @author dereza
 * 
 */
public class ReplenishCommand extends Command {

	private static final long serialVersionUID = 2051345145532653779L;

	private static Logger log = Logger.getLogger(ReplenishCommand.class);

	@Override
	public String execute(HttpServletRequest req, HttpServletResponse res) {
		log.debug("Command started");

		// gets client's session
		HttpSession session = req.getSession(false);

		// gets ClientBean from session
		ClientBean clientBean = (ClientBean) session.getAttribute("clientbean");
		log.trace("Got clientbean  from session --> " + clientBean);

		// if clientBean == null forward to login page
		if (clientBean == null) {
			String forward = Constants.COMMAND_LOGOUT;
			return forward;
		}

		// gets card id from request
		int cardId = Integer.parseInt(req.getParameter("id"));
		log.trace("got id card --> " + cardId);

		// gets sum of money for operation
		double sumUnconverted = Double.parseDouble(req.getParameter("sum"));
		BigDecimal sumForWithdraw = BigDecimal.valueOf(sumUnconverted)
				.setScale(2, BigDecimal.ROUND_DOWN);
		log.trace("got sum of money --> " + sumForWithdraw);

		// creates the required DAO generator
		MysqlDAOFactory mysqlFactory = (MysqlDAOFactory) DAOFactory
				.getDAOFactory(DAOFactory.MYSQL);

		// creates DAO for card
		CardDAO cardDAO = mysqlFactory.getCardDAO();
		CardDTO cardDTO = cardDAO.findClientCardById(cardId);

		// error handler
		String errorMessage = null;
		String forward = Constants.PAGE_ERROR_PAGE;
		if (cardDTO == null) {
			errorMessage = "Internal error. Cannot find card";
			req.setAttribute("errorMessage", errorMessage);
			log.error("errorMessage --> " + errorMessage);
			return forward;
		}
		log.trace("Found card in db --> " + cardDTO);

		// gets balance from account
		BigDecimal balance = cardDTO.getBalance();
		log.trace("Card balance --> " + balance);

		// gets status of card from account
		int statusId = cardDTO.getStatus_id();
		StatusDAO statusDAO = mysqlFactory.getStatusDAO();
		StatusDTO statusDTO = statusDAO.findStatusById(statusId);
		String status = statusDTO.getName();
		log.trace("Card status --> " + status);

		// check ability operation
		if (status.equals(Constants.STATUS_LOCKED)) {
			errorMessage = "Cannot execute operation, because card is locked";
			req.setAttribute("errorMessage", errorMessage);
			log.error("errorMessage --> " + errorMessage);
			return forward;
		}

		// execute operation
		try {
			cardDAO.updateBalance(cardId, balance.add(sumForWithdraw));
		} catch (Error e) {
			errorMessage = "Cannot execute operation";
			req.setAttribute("errorMessage", errorMessage);
			log.error("errorMessage --> " + errorMessage);
			return forward;
		}
		log.info(clientBean.getLogin() + " --> replenished " + sumForWithdraw
				+ " to card with id --> " + cardId);

		log.debug("Command finished");
		forward = Constants.COMMAND_CLIENT_LIST_CARDS;
		return forward;
	}

	@Override
	public String toString() {
		return "ReplenishCommand";
	}

}
